`define ASCII_OFFSET 8'd48

module Top(
    input  logic       sys_clk, rst, s1, s2, s3, s4,
    output logic       led1, uart_tx, uart_rx,
    output logic [7:0] seg_sel, seg_data
);

// 系统时钟生成
logic clk_scan, clk_debounce;
clkDiv clkDiv_inst(.*);

// //按键消抖模块信号声明
logic s1_debounced;
logic s2_debounced;
logic s3_debounced;
logic s4_debounced;

// 消抖信号处理
Debounce debounce_s1(
    .button_in(s1),
    .button_out(s1_debounced),
    .*
);

Debounce debounce_s2(
    .button_in(s2),
    .button_out(s2_debounced),
    .*
);

Debounce debounce_s3(
    .button_in(s3),
    .button_out(s3_debounced),
    .*
);

Debounce debounce_s4(
    .button_in(s4),
    .button_out(s4_debounced),
    .*
);


// 计数器信号
logic [4:0] ge, shi, bai;
logic isRunning_Out;

// 数码管显示数据（动态更新）
logic [4:0] data [0:7];
always_comb begin
    data = '{5'd12,5'd21,5'd21,5'd21,5'd21,5'd21,5'd21,5'd0};
    case(1)
        (bai > 0): data[5:7] = {bai, shi, ge};
        (shi > 0): data[6:7] = {shi, ge};
        default:    data[7] = ge;
    endcase
end

// UART数据生成
logic [7:0] uart_tx_data [0:31];

always_comb begin
    // 默认初始化
    uart_tx_data = '{default:8'hFF};
    uart_tx_data[0:5] = {8'h43, 8'h4F, 8'h55, 8'h4E, 8'h54, 8'h3A}; // "COUNT:"
    
    // 动态数字部分
    case(1)
        (bai > 0): begin
            uart_tx_data[6] = 8'(bai) + `ASCII_OFFSET; // 显式位宽转换
            uart_tx_data[7] = 8'(shi) + `ASCII_OFFSET;
            uart_tx_data[8] = 8'(ge) + `ASCII_OFFSET;
            uart_tx_data[9] = 8'hFF;  // 终止符
        end
        (shi > 0): begin
            uart_tx_data[6] = 8'(shi) + `ASCII_OFFSET;
            uart_tx_data[7] = 8'(ge) + `ASCII_OFFSET;
            uart_tx_data[8] = 8'hFF;
        end
        default: begin
            uart_tx_data[6] = 8'(ge) + `ASCII_OFFSET;
            uart_tx_data[7] = 8'hFF;
        end
    endcase
end

// 模块实例化
Counter counter_inst(
    .s1(s1_debounced),  // s1
    .s2(s2_debounced),  // s2 
    .s3(s3_debounced),  // s3
    .*
);

Display display_inst(
    .en(1'b1),         // 连接更新后的数据
    .decimal('0),
    .*
);

Led led_inst(.*);

logic uart_tx_busy;
logic uart_rx_en;
logic uart_rx_done;
logic [7:0] uart_rx_data;

Uart uart_inst(
    .sys_clk(sys_clk),
    .rst(rst),
    .uart_tx_en(s4_debounced),  // s4
    .*
);

endmodule